/**
 * test script for backbone.js
 *
 * author: Kensaku KOMATSU
 * created_at: 2011/6/7(tue)
 */

// $('ul').append("<li>hello</li>");
//
window.Store = function(name){
  this.name = name;
  var store = localStorage.getItem(this.name);
  this.data = (store && JSON.parse(store)) || {};
}

_.extend(Store.prototype, {
  save: function() {
    localStorage[this.name] = JSON.stringify(this.data);
  },

  create: function(model) {
    model.id = _.uniqueId();
    this.data[model.id] = model;
    this.save();
    return model
  },
  update: function(model) {
    this.data[model.id] = model;
    this.save();
    return model;
  },
  find: function(model){
    return this.data[model.id];
  },
  findAll: function(){
    return this.data;
  },
  destroy: function(model){
    delete this.data[model.id];
    this.save();
    return model;
  }
});


Backbone.sync = function(method, model, success, error) {
  var resp;
  var store = model.localStorage || model.collection.localStorage;
  console.log(method);
  switch(method){

    case "read": resp = model.id ? store.find(model) : store.findAll(); break;
    case "create": resp = store.create(model); break;
    case "update": resp = store.update(model); break;
    case "delete": resp = store.destroy(model); break;
  }
};

$(function(){
  window.Todo = Backbone.Model.extend({
    initialize: function(){
      if(!this.get("content")) {
        this.set({"content": "EMPTY"});
      }
    }
  });
  window.Todos = Backbone.Collection.extend({
    model: Todo,
    // url: "/todos"
    localStorage: new Store("todos")
  });
  todos = new Todos;

  window.AppView = Backbone.View.extend({
    el: $("#appview"),
    events: {
      "keypress input": "onKeypress",
      "click #get": "onClickGet"
    },
    initialize: function(){
      this.input = this.$("input");
      todos.fetch();
    },
    onKeypress:function(e){
      if(e.keyCode != 13) return; // not [Enter]
      todos.create({content:this.input.val()});
      this.input.val("");
    },
    onClickGet:function(){
    }
  });


  window.App = new AppView();
});
